#!/usr/bin/env python
#coding:utf-8
from django.shortcuts import render,HttpResponse,render_to_response,redirect
from  app01 import models
# Create your views here.


def login(request):

    '''
    t1 = models.UserType.objects.create(name='超级管理员')
    t2 = models.UserType.objects.create(name='普通管理员')
    u1 = models.UserInfo.objects.create(username='alex',password='123',gender=1,email='1@qq.com',user_type=t1)
    groupObj = models.UserGroup.objects.create(GroupName='主机A')
    groupObj.user.add(u1)
    '''

    ret = {'status':''}

    if request.method == 'POST':
        username = request.POST.get('username',None)
        password = request.POST.get('password',None)
        is_auth = all([username,password])
        if is_auth:
            count = models.UserInfo.objects.filter(username=username,password=password).count()
            if count == 1:
                return  redirect('/app01/index/')
            else:
                ret['status'] = '用户名或秘密错误.'
        else:
            ret['status'] = '用户名或密码不能为空.'
    return  render_to_response('app01/login.html',ret)


def index(request):
    return  render_to_response('app01/index.html')


def host(request):
    ret = {'status':"",'data':None,'group':None}
    usergroup = models.UserGroup.objects.all()
    ret['group'] = usergroup

    #新建主机
    if request.method == 'POST':
        hostname = request.POST.get('hostname',None)
        ip = request.POST.get('ip',None)
        groupId = request.POST.get('group',None)
        #验证用户输入是否为空
        is_auth = all([hostname,ip])
        if is_auth:
            groupObj = models.UserGroup.objects.get(id=groupId)
            models.Asset.objects.create(hostname=hostname,ip=ip,user_group=groupObj)
        else:
            ret['status'] = 'hostname或ip不能为空.'



    data = models.Asset.objects.all()
    ret['data'] = data
    return  render_to_response('app01/host.html',ret)